const qiniu = require('qiniu');  // 引入 qiniu
const nanoid = require('nanoid');  // 引入 nanoid 生成随机 id

const options = {
  Bucket: 'koa-prevue-resource',  // 仓库名
  Access_Key: 'Cz6YowE-q5aA-lhqpmxFvbX0oTJo21rBW9oyTntj',  // AK
  Secret_Key: 'LeAu3woMd9xKudzWwXwLKwzkHmHYlWCLvqQTQM4u',  // SK
}

// 创建作者
const mac = new qiniu.auth.digest.Mac(options.Access_Key, options.Secret_Key);
// 创建配置对象
const config = new qiniu.conf.Config();
// 创建仓库管理对象
const bucketManager = new qiniu.rs.BucketManager(mac, config);

// 将资源上传(准确来说是将爬取到的网络资源转存)到七牛云
const uploadToQiniu = async (resUrl, key) => {
  return new Promise((resolve, reject) => {
    // 调用 fetch 方法上传资源到七牛云
    bucketManager.fetch(resUrl, options.Bucket, key, (err, respBody, respInfo) => {
      if (err) {
        reject(err);
      } else {
        if (respInfo.statusCode == 200) {
          resolve({ key });
        } else {
          reject(respInfo);
        }
      }
    });
  });
}

(async () => {
  const movies = [{ 
    doubanId: '30221757',
    imgUrl: 'https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2563630521.jpg',
    videoSrc: 'http://vt1.doubanio.com/201910091529/e4e224134c13793fece12076a64087e4/view/movie/M/402500686.mp4',
    preImg: 'https://img1.doubanio.com/img/trailer/medium/2564316917.jpg?'
  }];

  movies.map(async (movie) => {
    if (movie.videoSrc && !movie.key) {
      // 如果 movie 不为空，并且没有 key 时，上传
      try {
        const videoData = await uploadToQiniu(movie.videoSrc, nanoid() + '.mp4');
        const imgUrlData = await uploadToQiniu(movie.imgUrl, nanoid() + '.jpg');
        const preImgData = await uploadToQiniu(movie.preImg, nanoid() + '.jpg');

        if (videoData.key) {
          movie.videoKey = videoData.key;
        }
        if (imgUrlData.key) {
          movie.imgUrlKey = imgUrlData.key;
        }
        if (preImgData.key) {
          movie.preImgKey = preImgData.key;
        }

        console.log('This movie is: ', movie);
      } catch (e) {
        console.log(e);
      }
    }
  });
})();
